package org.ycx.upms.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ycx.common.annotation.BaseService;
import org.ycx.common.base.BaseServiceImpl;
import org.ycx.common.db.DataSourceEnum;
import org.ycx.common.db.DynamicDataSource;
import org.ycx.upms.dao.mapper.ISecRoleMapper;
import org.ycx.upms.dao.mapper.ISecRolePermissionMapper;
import org.ycx.upms.dao.model.*;
import org.ycx.upms.service.ISecRoleService;

import java.util.List;

/**
 * SecRoleService实现
 * Created by yang on 2017-07-19 15:16:03.
 */
@Service
@Transactional
@BaseService
public class SecRoleServiceImpl extends BaseServiceImpl<ISecRoleMapper, SecRole, SecRoleExample> implements ISecRoleService {

    private static Logger _log = LoggerFactory.getLogger(SecRoleServiceImpl.class);

    @Autowired
    ISecRoleMapper mapper;

    @Autowired
    ISecRolePermissionMapper rpMapper;

    @Override
    public List<Integer> selectByRoleId(Integer id) {
        DynamicDataSource.setDataSource(DataSourceEnum.SLAVE.getName());
        return this.mapper.selectByRoleId(id);
    }

    @Override
    public int updateGrant(Integer rid, String ids) {
        int res = 0;
        DynamicDataSource.setDataSource(DataSourceEnum.MASTER.getName());
        SecRolePermissionExample spe = new SecRolePermissionExample();
        spe.createCriteria().andRoleIdEqualTo(rid);
        res += this.rpMapper.deleteByExample(spe);
        if (null != ids && ids.length() > 1) {
            String id[] = ids.split("-");
            for (int i = 0; i < id.length; i++) {
                SecRolePermission srp = new SecRolePermission();
                srp.setInherit(1);
                srp.setRoleId(rid);
                srp.setPermissionId(Integer.parseInt(id[i]));
                res += this.rpMapper.insert(srp);
            }
        }
        return res;
    }
}